/* eslint-disable import/first,no-throw-literal */
import * as mydemoService from '../services/myDemo';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'mydemo',
  state: {
    message: {
      dataList: null,
      total: null,
    },
    total: null,
    page: null,
    queryStr: null,
  },
  reducers: {
    mydata(state, { payload: { data: message, total, page, queryStr } }) {
      return { ...state, message, total, page, queryStr };
    },
  },
  effects: {
    *findAllByPage({ payload: { page = 1, queryStr = '' } }, { call, put }) {
      const { data } = yield call(mydemoService.findAllByPage, { page, queryStr });
      yield put({
        type: 'mydata',
        payload: {
          data,
          total: parseInt(data.total, 10),
          page: parseInt(page, 10),
          queryStr,
        },
      });
    },
    *deleteUser({ payload: id }, { call, put }) {
      yield call(mydemoService.deleteUser, id);
      yield put({ type: 'reload' });
    },
    *insertUser({ payload: values }, { call, put }) {
      const { data } = yield call(mydemoService.insertUser, values);
      if (data && data.state === 'SUCCESS') {
        yield put(routerRedux.push('/mydemo'));
      } else {
        throw { data };
      }
    },
    *updateUser({ payload: values }, { call, put }) {
      const { data } = yield call(mydemoService.updateUser, values);
      if (data && data.state === 'SUCCESS') {
        yield put({ type: 'reload' });
      } else {
        throw { data };
      }
    },
    *reload(action, { put, select }) {
      const { page, queryStr } = yield select(state => state.mydemo);
      yield put({ type: 'findAllByPage', payload: { page, queryStr } });
    },
  },
  subscriptions: {
    reRead({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/mydemo') {
          dispatch({ type: 'findAllByPage', payload: query });
        }
      });
    },
  },
};
